package org.jdns.jfreechess.server;

import io.netty.channel.Channel;
import io.netty.util.AttributeKey;

import java.util.concurrent.atomic.AtomicLong;

import com.google.common.base.Function;
import com.google.common.base.Objects;

/**
 * Represents a user of the chess server.
 */
public class User {
  public static final AttributeKey<User> CHANNEL_ATTRIBUTE_KEY = new AttributeKey<User>("user");

  public static final Function<User, String> NAME_FUNCTION = new Function<User, String>() {
    @Override
    public String apply(User input) {
      return input.getName();
    }
  };

  private final String name;
  private final Channel channel;
  
  private final AtomicLong lastCommandTime;
  
  private User(Channel channel, String name, boolean isAuthenticated) {
    this.channel = channel;
    this.name = name;
    this.lastCommandTime = new AtomicLong(System.currentTimeMillis());
  }

  public static User authenticatedUser(Channel channel, String name) {
    return new User(channel, name, true);
  }

  /**
   * Returns a user for testing. This user has no channel.
   */
  public static User userForTesting(String name) {
    return new User(null, name, true);
  }

  public String getName() {
    return name;
  }

  public Channel getChannel() {
    return channel;
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(this).add("name", name).toString();
  }

  public void resetLastCommandTime() {
    lastCommandTime.set(System.currentTimeMillis());
  }
}
